const router = require('koa-router')();
const {
	getList,
	getDetail,
	del,
	newBlog,
	upDateBlog,
} = require('../function/blog.js')
const loginCheck = require('../middleware/loginCheck.js')

router.prefix('/api/blog');
router.get('/list', async (ctx, next) => {
	let query = ctx.query; // 获取get传入的数据
	let author = query.author || "";
	let keyword = query.keyword || "";
	let res = await getList(author, keyword)
	ctx.body = {
		errno: 0,
		data: res
	};
});
router.get('/detail', async (ctx, next) => {
	let id = ctx.query.id || "";
	let res = await getDetail(id)
	ctx.body = {
		errno: 0,
		data: res
	}
})

router.post('/del', loginCheck, async (ctx, next) => {
	let id = ctx.request.body.id || ""
	let author = ctx.session.username || "";
	// let res = await del(id,author)
	ctx.body = {
		errno: 0,
		id,
		data: res
	}
})

router.post('/newBlog',  async (ctx, next) => {
	let newBlogData = ctx.request.body;
	newBlogData.author = ctx.session.username;
	// const resd = await newBlog(newBlogData)
	// // console.log(resd);
	// ctx.body = "123123"
	// // ctx.body = {
	// // 	errno: 0,
	// // 	data: resd
	// // }
	
	// let res = await newBlog(newBlogData)
	newBlog(newBlogData).then(e=>{
		console.log(e);
		if(e.affectedRows != 0 ){
			return ctx.body = {
				errno:0,
				data:'新建成功'
			};
		}else{
			return ctx.body = {
				errno:0,
				data:'新建失败'
			};
		}
	});
})
module.exports = router;
